#include "widget.h"
#include "ui_widget.h"
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("Client");
    resize(600,480);

    // 1.创建QTcpSocker对象
    m_socker = new QTcpSocket(this);

    // 3.连接信号
    connect(m_socker, &QTcpSocket::readyRead, [=]{
        // 读取服务器数据
        QByteArray messageFromServer = m_socker->readAll();
        ui->listWidget->addItem(QString(">>> Client received message from Server：") + QString::fromUtf8(messageFromServer));
    });

    // 2.连接到指定服务器
    m_socker->connectToHost("127.0.0.1", 8888);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    // 要发送的数据
    QString message = ui->lineEdit->text();

    // 将数据发送给服务器
    m_socker->write(message.toUtf8());

    // 将发送的数据显示在listWidget上
    ui->listWidget->addItem(QString("Client sended message to Server：") + message);

    // 清空输入框数据
    ui->lineEdit->clear();
}
